//
//  AddOrderViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/5/12.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "AddOrderViewController.h"
#import "AddOrderTableViewCell.h"
#import "AddOrderFooterView.h"
#import "SelectPayWayView.h"
#import "MyReceiveAddressViewController.h"
#import "theOrderView.h"

@interface AddOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *address;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) AddOrderFooterView *footerView;
@property (nonatomic,strong) UIView *funcView;
@property (nonatomic,strong) UILabel *priceLabel;

@property (nonatomic,strong) NSDictionary *dataDictionary;

@property (nonatomic,assign) BOOL everScore;
@property (nonatomic,assign) BOOL timeScore;
@property (nonatomic,assign) BOOL allScore;
- (void)paymentClick;

@end

//网络
@implementation AddOrderViewController (NetWorking)

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auId":[UserModel sharedInstanced].userId,
                                 @"s_id":self.sId,
                                 @"c_id":self.cId,
                                 @"ocl_num":self.num};
    [[AFAppDotNetAPIClient sharedClient] POST:@"OrderInformationMoblie/insertOI.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"ResponseStatus"] isEqualToString:@"0"]) {
            self.dataDictionary = responseObject[@"obj"];
            address = self.dataDictionary[@"auAddress"];
            [self.view addSubview:self.tableView];
            [self.view addSubview:self.funcView];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getUpdateOstate:(NSString *)str{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"o_id":@"",
                                 @"o_state":str};
    [[AFAppDotNetAPIClient sharedClient] POST:@"OrderInformationMoblie/updateOstate.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"ResponseStatus"] isEqualToString:@"0"]) {
            [self paymentClick];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

//UI
@implementation AddOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"确认订单";
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

#pragma mark - Event

- (void)setupPriceInfo{
    self.footerView = nil;
    self.tableView.tableFooterView = self.footerView;
    NSMutableAttributedString *attStr = [NSMutableAttributedString new];
    if (self.everScore) {
        NSLog(@"永久积分");
        NSString *tmp1 = [NSString stringWithFormat:@"使用永久积分%@分可抵%@元\n",self.dataDictionary[@"use_limit_integral"],self.dataDictionary[@"ermanent_integral_bonus"]];
        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:tmp1]];
    }if (self.timeScore) {
        NSLog(@"限时积分");
        NSString *tmp2 = [NSString stringWithFormat:@"使用限时积分%@分可抵%@元\n",self.dataDictionary[@"use_permanent_points"],self.dataDictionary[@"time_limited_integration"]];
        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:tmp2]];
    }
    if (self.allScore) {
       
        NSString *tmp3 = [NSString stringWithFormat:@"使用永久积分%d分全部购买商品\n",[self.dataDictionary[@"commodity_integral"] intValue]];
        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:tmp3]];
    }
    int a = [self.dataDictionary[@"ocl_num"] intValue] * [self.dataDictionary[@"c_unit_price"] intValue];
    NSString *allPrice = [NSString stringWithFormat:@"¥%d",a];
    NSString *realPrice;
    if (self.everScore) {
        NSLog(@"永久积分");
        realPrice = [NSString stringWithFormat:@"¥%d",a - [self.dataDictionary[@"ermanent_integral_bonus"] intValue]];
    }else if (self.timeScore) {
        realPrice = [NSString stringWithFormat:@"¥%d",a - [self.dataDictionary[@"time_limited_integration"] intValue]];
    }else if (self.allScore) {
        realPrice = [NSString stringWithFormat:@"¥%d",0];
    }else if(self.everScore && self.timeScore){
        realPrice = [NSString stringWithFormat:@"¥%d",a - [self.dataDictionary[@"time_limited_integration"] intValue] - [self.dataDictionary[@"ermanent_integral_bonus"] intValue]];
    }else{
        realPrice = [NSString stringWithFormat:@"¥%d",a];
    }
    [attStr appendAttributedString:[self getAttributeName:allPrice info:realPrice]];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:3];//调整行间距
    [paragraphStyle setAlignment:NSTextAlignmentCenter];
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attStr length])];
    _priceLabel.attributedText = attStr;

}

- (NSAttributedString *)getAttributeName:(NSString *)name info:(NSString *)info{
    NSMutableAttributedString *attStr = [NSMutableAttributedString new];
    NSAttributedString *nameAtt = [[NSAttributedString alloc]initWithString:name attributes:@{NSForegroundColorAttributeName:getColor(mainColor)}];
    NSAttributedString *infoAtt = [[NSAttributedString alloc]initWithString:info attributes:@{NSForegroundColorAttributeName:getColor(mainColor)}];
    [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"总价: "]];
    [attStr appendAttributedString:nameAtt];
    [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"   实付: "]];
    [attStr appendAttributedString:infoAtt];
    
    return attStr;
}

- (void)submitEvent{
    theOrderView *view = [[theOrderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString *str) {
        NSLog(@"%@",str);
        if ([str isEqualToString:@"0"]) {
            [self getUpdateOstate:@"1"];
        }else{
            [self getUpdateOstate:@"0"];
        }
        
    }];
    
    [view show];
}

- (void)paymentClick{
    NSLog(@"付款点击事件");
    SelectPayWayView *view = [[SelectPayWayView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    view.typeSelectHandle = ^(NSUInteger index) {
        NSLog(@"%lu",(unsigned long)index);
    };
    [view show];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AddOrderTableViewCell class])];
    cell.dataDictionary = self.dataDictionary;
    return cell;
}

#pragma mark - set & get

- (UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-50) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 4;
        _tableView.sectionHeaderHeight = 25;
        _tableView.tableFooterView = self.footerView;
        _tableView.tableHeaderView = self.headerView;
        _tableView.rowHeight = 70;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[AddOrderTableViewCell class] forCellReuseIdentifier:NSStringFromClass([AddOrderTableViewCell class])];
    }
    return _tableView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 25)];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 25)];
        view.backgroundColor = [UIColor whiteColor];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 25)];
        label.textColor = getColor(mainColor);
        label.font = DEF_FontSize_11;
        
        NSMutableAttributedString *attStr = [NSMutableAttributedString new];
        NSTextAttachment *imgAtt = [NSTextAttachment new];
        imgAtt.image = [UIImage imageNamed:@"shop1"];
        imgAtt.bounds = CGRectMake(0, -3, 15, 15);
        [attStr appendAttributedString:[NSAttributedString attributedStringWithAttachment:imgAtt]];
        [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"  %@",self.dataDictionary[@"s_name"]]]];
        label.attributedText = attStr;
        
        [view addSubview:label];
        [_headerView addSubview:view];
    }
    return _headerView;
}

- (AddOrderFooterView *)footerView{
    if (!_footerView) {
        _footerView = [[AddOrderFooterView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200 + 200)];
        __block typeof(self) bSelf = self;
        _footerView.address = address;
        _footerView.timeScore = self.timeScore;
        _footerView.everScore = self.everScore;
        _footerView.allScore = self.allScore;
        _footerView.model = self.dataDictionary;
        _footerView.selectEverScoreHandle = ^{
            bSelf.everScore =! bSelf.everScore;
            bSelf.allScore = NO;
            [bSelf setupPriceInfo];
        };
        _footerView.selectTimeScoreHandle = ^{
            bSelf.timeScore =! bSelf.timeScore;
            bSelf.allScore = NO;
            [bSelf setupPriceInfo];
        };
        _footerView.selectAllScoreHandle = ^{
            bSelf.allScore = ! bSelf.allScore;
            bSelf.everScore = NO;
            bSelf.timeScore = NO;
            [bSelf setupPriceInfo];
        };
        _footerView.getAddressClick = ^{
            MyReceiveAddressViewController *vc = [MyReceiveAddressViewController new];
            vc.getAddress = ^(NSString *str) {
                address = str;
                [bSelf setupPriceInfo];
            };
            [bSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _footerView;
}

- (UIView *)funcView{
    if (!_funcView) {
        _funcView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-64-50, SCREEN_WIDTH, 50)];
        _funcView.backgroundColor = getColor(mainColor);
        
        [_funcView addSubview:({
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-100, 0, 100, 50)];
            [btn setTitle:@"提交订单" forState:UIControlStateNormal];
            btn.titleLabel.font = DEF_FontSize_15;
            btn.backgroundColor = getColor(mainColor);
            [btn addTarget:self action:@selector(submitEvent) forControlEvents:UIControlEventTouchUpInside];
            btn;
        })];
        
        [_funcView addSubview:({
            _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH-100, 49)];
            _priceLabel.textAlignment = NSTextAlignmentCenter;
            _priceLabel.font = DEF_FontSize_10;
            _priceLabel.backgroundColor = [UIColor whiteColor];
            _priceLabel.numberOfLines = 0;;
            _priceLabel;
        })];
        
        [self setupPriceInfo];

    }
    return _funcView;
}

- (NSDictionary *)dataDictionary{
    if (!_dataDictionary) {
        _dataDictionary = @{};
    }
    return _dataDictionary;
}

- (void)setNum:(NSString *)num{
    _num = num;
    [self getData];
}

@end
